package com.xwdeshj.intercepter;

import com.xwdeshj.utils.CookieUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by BKWJA on 2018/11/19.
 *  @Configuration：拦截器
 */
@Configuration
public class LoginIntercepter extends WebMvcConfigurerAdapter {

    public final static String SESSION_KEY = "token";

    /**
     * 配置servlet处理
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }


    public void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor( getSecurityInterceptor());

        //排除的路径
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/err");
        addInterceptor.excludePathPatterns("/login.html");
        addInterceptor.excludePathPatterns("/404.html");
        addInterceptor.excludePathPatterns("/login");

        addInterceptor.excludePathPatterns("/js/**");
        addInterceptor.excludePathPatterns("/css/**");
        addInterceptor.excludePathPatterns("/font/**");
        addInterceptor.excludePathPatterns("/lib/**");
        addInterceptor.excludePathPatterns("/static/**");
        addInterceptor.excludePathPatterns("/images/**");
        addInterceptor.excludePathPatterns("/forceModifyPassword"); //强制更改密码
        addInterceptor.excludePathPatterns("/swagger-ui.html"); //swagger

        /**
         * 拦截器按照顺序执行
         * /** : 拦截所有路径
         */
        addInterceptor.addPathPatterns("/**");
    }


    //判断用户是否登录
    private class SecurityInterceptor extends HandlerInterceptorAdapter {

        /**
         * 在请求处理之前进行调用（Controller方法调用之前）
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws IOException, IOException {
            String token = CookieUtils.getCookieValue(request,SESSION_KEY);
            String url = request.getRequestURL().toString(); //获取当前的url链接
            //判断是否已有该用户登录的session
            if (token != null && token != "") {  //是否放行
                return true;
            }
            //跳转到登录页
            response.sendRedirect("login");
            return false;
        }
    }
}
